<?php

namespace app\model;

use think\facade\Cache;
use think\Model;

class BocMenu extends Model
{
    protected $sort = 'sort desc, create_at';

    public function get_list()
    {
        $key = 'menu';
        $list = Cache::get($key);
        if (empty($list)) {
            //获取父级菜单
            // $list = $this->where(['pid' => 0, 'status' => 1, 'is_deleted' => 0])->order($this->sort)->select()->toArray();
            // foreach ($list as $k => &$v) {
            //     $c = $this->where(['pid' => $v['id'], 'status' => 1, 'is_deleted' => 0])->order($this->sort)->select()->toArray();
            //     if (!empty($c)) {
            //         $list[$k]['c'] = $c;
            //     }
            // }

            $data = $this->where(['status' => 1, 'is_deleted' => 0])->order($this->sort)->select()->toArray();
            $list = $this->getChild($data);
            Cache::tag('menu')->set($key, $list);
        }

        return $list;
    }

    public function getChild($data, $pid = 0)
    {
        $array = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                $array[$k] = $v;
                unset($data[$k]);
                $array[$k]['children'] = $this->getChild($data, $v['id']);
            }
        }

        return $array;
    }
}
